<?php


namespace app\suguan\controller;

use app\suguan\utils\User as AdminUser;
use think\Db;

class Shebei extends Base
{
    public function index()
    {
        $page = request()->param('page', 1, 'intval');
        $limit = request()->param('limit', 20, 'intval');
        $room_id = request()->param('room_id', '');
        $where = [];
        $house_id = $this->house_id();
        $room = model('Room')->where('house_id', $house_id)->column('title', 'id');
        $where[] = ['house_id', '=', $house_id];
        if ($room_id) {
            $where[] = ['room_id', '=', $room_id];
        }
        $list = Db::name('shebei')->where($where)->page($page, $limit)->select();
        foreach ($list as $k => $v) {
            $list[$k]['room_id'] = model('Room')->where('id', $v['room_id'])->value('title');
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        $total = Db::name('shebei')->where($where)->count();
        $data = [
            'list' => $list,
            'total' => $total,
            'room' => $room
        ];
        return $this->ok($data);
    }

    public function detail()
    {
        $id = request()->param('id', 0, 'intval');
        if (!$id) {
            return $this->fail('参数错误');
        }
        $detail = Db::name('shebei')->find($id);
        $house_id = $this->house_id();
        $detail['room'] = model('Room')->where('house_id', $house_id)->column('title', 'id');
        if (empty($detail)) {
            return $this->fail('查无该设备信息');
        }
        return $this->ok($detail);
    }

    public function save()
    {
        $params = request()->only(['room_id', 'title', 'id']);
        $params['house_id'] = $this->house_id();
        try {
            model('Shebei')->saveData($params);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
        return $this->ok('操作成功');
    }

    public function delete()
    {
        $id = request()->param('id', '');
        $res = model('Shebei')->where('id', 'in', $id)->delete();
        if ($res) {
            return $this->ok('删除成功');
        } else {
            return $this->fail('删除失败');
        }
    }
}